﻿using Microsoft.AspNet.SignalR;
using Microsoft.Owin.FileSystems;
using Microsoft.Owin.StaticFiles;
using Owin;
using Sustainalytics.Synchronization.BusinessLogic;
using System;
using System.IO;
using System.Timers;
using System.Web.Http;

namespace Sustainalytics.Synchronization.Service
{
    public class Startup
    {
        private static DateTime _creationDay { get; set; }
        public static void Configuration(IAppBuilder app)
        {
            var options = new FileServerOptions
            {
                EnableDirectoryBrowsing = false,
                FileSystem = new PhysicalFileSystem("app")
            };

            app.UseFileServer(options);

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            app.UseWebApi(config);

            app.Map("/signalr", map =>
            {
                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors = true,
                    EnableJSONP = true
                };

                map.RunSignalR(hubConfiguration);
            });

            StartTimer();

            config.EnsureInitialized();
            var syncronizationEngine = new SyncronizationEngine();

            Globals.Sync = syncronizationEngine;
        }

        public static void StartTimer()
        {
            Timer aTimer = new Timer();
            aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            aTimer.Interval = 3600 * 1000;
            aTimer.Enabled = true;
        }

        public static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            string filepath = AppDomain.CurrentDomain.BaseDirectory + @"\Log\";

            string filename = filepath + "log.txt";

            if (File.Exists(filename))
            {
                _creationDay = File.GetCreationTime(filename);
                if (_creationDay.AddDays(20).Date == DateTime.Now.Date)
                {
                    File.Delete(filename);
                }
            }
        }

        protected Startup()
        {

        }
    }
}
